const Koa = require('koa');
const app = new Koa();
const views = require('koa-views');
const json = require('koa-json');
const onerror = require('koa-onerror');
const bodyparser = require('koa-bodyparser');
const logger = require('koa-logger');
const path = require('path');
const cors = require('koa2-cors');
const log4js = require('./middleware/log4.js');
const auth = require('./middleware/auth.js');
const wx = require('./middleware/wx.js');
const error = require('./middleware/error.js');
require('./libs/db.js')();
const index = require('./routes/index');
const users = require('./routes/users');
const common = require('./routes/common.js');
const film = require('./routes/film.js');
const dianshang = require('./routes/dianshang.js');
const comment = require('./routes/comment.js');
const cart = require('./routes/cart.js');
const order = require('./routes/order.js');
const wxR = require('./routes/wxRoute.js');

// error handler
onerror(app);
process.env.dataDir = __dirname;
// middlewares
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}));
app.use(json());
app.use(log4js);
app.use(logger());
app.use(require('koa-static')(path.resolve(__dirname, '/public')));
app.use(views(path.resolve(__dirname, '/views'), {
  extension: 'ejs'
}));

app.use(cors({
  origin: function (ctx) {
    if (ctx.url === '/test') {
      return false;
    }
    return '*';
  },
  exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
  maxAge: 5,
  credentials: true,
  allowMethods: ['GET', 'POST', 'DELETE'],
  allowHeaders: ['Content-Type', 'Authorization', 'Accept', 'token']
}));
app.use(error);
app.use(auth);
app.use(wx);
// logger
app.use(async (ctx, next) => {
  const start = new Date();
  await next();
  const ms = new Date() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});

// routes
app.use(index.routes(), index.allowedMethods());
app.use(users.routes(), users.allowedMethods());
app.use(common.routes(), common.allowedMethods());
app.use(film.routes(), film.allowedMethods());
app.use(dianshang.routes(), dianshang.allowedMethods());
app.use(comment.routes(), comment.allowedMethods());
app.use(cart.routes(), cart.allowedMethods());
app.use(order.routes(), order.allowedMethods());
app.use(wxR.routes(), wxR.allowedMethods());
// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx);
  ctx.log.error(`发生错误:${err}`);
});

module.exports = app;
